<template>
  <div>
    <div class="btn_box" style="margin: 20px 0">
      <el-button type="primary" @click="handleAdd">创建角色</el-button>
    </div>
    <el-table :data="users" height="380" border style="width: 100%">
      <el-table-column type="index" label="序号" width="60"> </el-table-column>
      <el-table-column prop="username" label="用户名"> </el-table-column>
      <el-table-column prop="name" label="姓名"> </el-table-column>
      <el-table-column prop="phone" label="电话"> </el-table-column>
      <el-table-column
        prop="create_time"
        label="创建时间"
        :formatter="reseDate"
      >
      </el-table-column>
      <el-table-column prop="role_id" label="所属角色" :formatter="formatRole">  </el-table-column>
      <el-table-column label="操作" width="250">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row._id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDele(scope.row._id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 添加/编辑弹窗 -->
    <el-dialog title="用户编辑" :visible.sync="userFormVisible" width="500px">
      <el-form
        :model="user"
        ref="userForm"
        label-width="100px"
        label-position="right"
        style="width: 400px"
        :rules="rules"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input
            v-model="user.username"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" type="password">
          <el-input
            v-model="user.password"
            placeholder="请输入用户密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="user.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select
            class="filter-item"
            v-model="user.role_id"
            placeholder="请点击选择"
          >
            <el-option
              v-for="option in roleOptions"
              :key="option._id"
              :label="option.name"
              :value="option._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model="user.phone"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="user._id==null ? addData('userForm') : updateData('userForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import { formateDate } from "@/utils/dateUtils.js";
import userApi from "@/api/user";
export default {
  data() {
    var validateUserName = (rule, value, callback) => {
      value = value.trim();
      const length = value && value.length;
      const pwdReg = /^[a-zA-Z0-9_]+$/;
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (length <= 4 || length > 12) {
        callback(new Error("账号长度应在4~12位之间"));
      } else if (!pwdReg.test(value)) {
        callback(new Error("账号组成只能包含英文数字或下划线"));
      } else {
        callback();
      }
    };
    var validatePhone = (rule, value, callback) => {
      value = value.trim();
      const phoneReg =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (value === "") {
        callback(new Error("请输入手机号码"));
      } else if (!phoneReg.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };

    return {
      userFormVisible: false,
      currentPage: 1,
      totalPage:1,
      pageSize: 5,
      total: 0,
      users: [],
      user: {
        _id: null,
          username: "",
          password: "",
          name: "",
          phone: "",
          role_id: "",
      },
      roleOptions: [],
      rules: {
        username: [
          {
            required: true,
            validator: validateUserName,
            trigger: ["blur", "change"],
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: ["blur", "change"],
          },
          {
            min: 4,
            message: "密码长度要大于或等于四位",
            trigger: ["blur", "change"],
          },
        ],
        name: [
          {
            required: true,
            message: "请输入姓名",
            trigger: ["blur", "change"],
          },
        ],
        role_id:[
          {
            required: true,
            message: "请选择角色",
            trigger: ["blur", "change"],
          }
        ],
        phone: [
          {
            required: true,
            validator: validatePhone,
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },

  components: {},
  mounted() {
    this.fetchUsers();
  },
  methods: {
    addData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          userApi.add(this.user).then(res=>{
            const resp = res.data
            if(resp.status == 0){
              this.$message({
                type:'success',
                message:'添加用户成功咯！'
              })
              this.userFormVisible = false
              this.fetchUsers()
            }
          })
        } else {
          return false;
        }
      });
    },
    updateData(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          userApi.update(this.user).then(res=>{
            const resp = res.data
            if(resp.status == 0){
              this.$message({
                type:'success',
                message:'修改用户信息成功咯！'
              })
              this.userFormVisible = false
              this.fetchUsers()
            }
          })
        } else {
          return false;
        }
      });
    },
    handleAdd() {
      this.user = {
          _id: null,
          username: "",
          password: "",
          name: "",
          phone: "",
          role_id: "",
        };
      this.userFormVisible = true;
      this.$nextTick(() => {
        this.$refs["userForm"].resetFields();
        
      });
    },
    fetchUsers() {
      if(this.currentPage>Math.ceil(this.totalPage)){
        this.currentPage=Math.ceil(this.totalPage)
      }
      userApi.getUserList(this.currentPage, this.pageSize).then((res) => {
        const resp = res.data;
        if (resp.status == 0) {
          this.users = resp.data.data;
          this.total =resp.data.total;
          this.roleOptions = resp.data.roles;
          this.totalPage = this.total/this.pageSize
        }
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.fetchUsers()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.fetchUsers()
    },
    reseDate(row, column, cellValue, index) {
      return formateDate(cellValue);
    },
    handleEdit(_id) {
      this.handleAdd();
      userApi.getByid(_id).then((res)=>{
        const resp = res.data;
        console.log(resp.data);
        if(resp.status==0){
          this.user=resp.data
          
        }

      })
    },
    handleDele(id) {
      console.log("删除");
      this.$confirm("确认删除这条记录吗？","提示",{
        confirmButtonText:"确定",
        cancelButtonText:"取消",
        type:"warning"
      }).then(()=>{
        userApi.deleteByid(id).then((res)=>{
          const resp = res.data;
          console.log(resp.data);
        if(resp.status==0){
          this.$message({
                type:'success',
                message:'删除用户成功咯！'
              })
              this.totalPage = (this.total-1)/this.pageSize
              this.fetchUsers()
          
        }
        })
      })
    },
    formatRole(row, column, cellValue, index) {
      const role = this.roleOptions.find((item) => item._id == cellValue) || {};
      return role.name;
    },
  },
};
</script>

<style scoped>
</style>